package com.quanyan.place.service.impl;

import com.quanyan.common.Plugin.Page;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.utils.DateTimeUtils;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.*;
import com.quanyan.place.entity.apireq.ReqBusinessAwardVo;
import com.quanyan.place.entity.vo.BusinessAwardUserVo;
import com.quanyan.place.entity.vo.PlaceVisitStatisVo;
import com.quanyan.place.mapper.*;
import com.quanyan.place.service.BusinessAwardService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by zhaohui on 2016/6/29.
 */
@Service
public class BusinessAwardServiceImpl implements BusinessAwardService {

    //private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    TbBizPlaceBusinessRewardRuleMapper tbBizPlaceBusinessRewardRuleMapper;

    @Autowired
    TbBizPlaceBusinessRewardRuleManagerMapper tbBizPlaceBusinessRewardRuleManagerMapper;

    @Autowired
    TbBizPlaceBusinessAgentStatisticsMapper tbBizPlaceBusinessAgentStatisticsMapper;

    @Autowired
    TbBizPlaceEmployeeMapper tbBizPlaceEmployeeMapper;

    @Autowired
    TbBizPlaceBusinessUserRewardMapper tbBizPlaceBusinessUserMapper;

    @Autowired
    TbBizPlaceVisitedMapper tbBizPlaceVisitedMapper;

    @Autowired
    TbBizPlaceBuyContractDetailMapper tbBizPlaceBuyContractDetailMapper;

    @Autowired
    TbAdminUserMapper tbAdminUserMapper;

    @Autowired
    TbBizPlaceRepresentMapper tbBizPlaceRepresentMapper;



    /**
     * 根据条件查询奖金规则
     *
     * @param reqBusinessAwardVo
     * @return
     */
    @Override
    public List<TbBizPlaceBusinessRewardRule> getRewardRuleByCondition(ReqBusinessAwardVo reqBusinessAwardVo) {
        List<TbBizPlaceBusinessRewardRule> list = null;
        try {
            TbBizPlaceBusinessRewardRuleExample rewardRuleExample = new TbBizPlaceBusinessRewardRuleExample();
            TbBizPlaceBusinessRewardRuleExample.Criteria rewardRuleExampleCriteria = rewardRuleExample.createCriteria();
            Integer cityId = reqBusinessAwardVo.getCityId();
            if (null != cityId) {
                rewardRuleExampleCriteria.andCityIdEqualTo(cityId);
            }
            Integer tagGroup = reqBusinessAwardVo.getTagGroup();
            if (null != tagGroup) {
                rewardRuleExampleCriteria.andTagGroupEqualTo(tagGroup);
            }
            Byte userRoleType = reqBusinessAwardVo.getUserRoleType();
            if (null != userRoleType) {
                rewardRuleExampleCriteria.andUserRoleTypeEqualTo(userRoleType);
            }
            Integer paramKey = reqBusinessAwardVo.getParamKey();
            if (null != paramKey) {
                rewardRuleExampleCriteria.andParamKeyEqualTo(paramKey);
            }
            Byte isEnabled = reqBusinessAwardVo.getIsEnabled();
            if (null != isEnabled) {
                rewardRuleExampleCriteria.andIsEnabledEqualTo(isEnabled);
            }else{
                rewardRuleExampleCriteria.andIsEnabledEqualTo(PlaceConstants.IS_EFFECTIVE_YES);
            }
            list = tbBizPlaceBusinessRewardRuleMapper.selectByExample(rewardRuleExample);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }



    /**
     * 修改系数（paramKey，userRoleType，tagGroup）
     *
     * @param reqBusinessAwardVo
     * @return
     */
    @Override
    public Integer updateRewardRuleCondition(ReqBusinessAwardVo reqBusinessAwardVo) {
        List<ReqBusinessAwardVo> getRewardRuleList = reqBusinessAwardVo.getList();
        Integer result = 0;
        try {
            for (ReqBusinessAwardVo getRewardRule:getRewardRuleList){
                Map<String, Object> map = new HashMap();
                Integer tagGroup = getRewardRule.getTagGroup();
                if (null != tagGroup) {
                    map.put("tagGroup", tagGroup);
                }
                Byte userRoleType = reqBusinessAwardVo.getUserRoleType();
                if (null != userRoleType) {
                    map.put("userRoleType", userRoleType);
                }
                BigDecimal minValue = getRewardRule.getParamMinValue();
                if (null != minValue) {
                    map.put("paramMinValue", minValue);
                }
                BigDecimal maxValue = getRewardRule.getParamMaxValue();
                if (null != maxValue) {
                    map.put("paramMaxValue", maxValue);
                }
                Integer paramKey = getRewardRule.getParamKey();
                if (null != paramKey) {
                    map.put("paramKey", paramKey);
                }
                BigDecimal coefficientValue = getRewardRule.getCoefficientValue();
                if (null != coefficientValue) {
                    map.put("coefficientValue", coefficientValue);
                }
                Byte isEnabled = getRewardRule.getIsEnabled();
                if (null != isEnabled) {
                    map.put("isEnabled", isEnabled);
                }
                result = tbBizPlaceBusinessRewardRuleManagerMapper.updateByCondition(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 统计商务代表上月有效，新有效拜访，签约整馆，时段，分片个数
     */
    @Override
    public void insertAgentStatis() {
        Map<String, Object> map = new HashMap<>();
        map.put("beginTime", DateTimeUtils.getBeforeFirstMonthdate());//获取上个月开始时间 格式 2016-05-01 00:00:00
        map.put("endTime", DateTimeUtils.getBeforeLastMonthdate()); //获取上个月结束时间 格式 2016-05-31 23:59:59
        List<Integer> result = new ArrayList<>();
        result.add(PlaceConstants.PLACE_VISIT_RESULT_TALKS);
        result.add(PlaceConstants.PLACE_VISIT_RESULT_PROPOSAL);
        result.add(PlaceConstants.PLACE_VISIT_RESULT_SIGN);
        map.put("result", result);
        //获取有效拜访
        isVisitCommonUpdateAndInsert(map, 1);
        //新有效拜访
        result.clear();
        result.add(PlaceConstants.PLACE_VISIT_RESULT_NEW_EFFECTIVE);
        map.put("result", result);
        isVisitCommonUpdateAndInsert(map,2);
        //整场
        List<Integer> allPlace = new ArrayList<>();
        allPlace.add(PlaceConstants.BUY_TYPE_WHOLE);
        map.put("buyWay", allPlace);
        map.put("finishDate",new Date());
        commonSignUpdateAndInsert(map, 3);
        //包片
        allPlace.clear();
        allPlace.add(PlaceConstants.BUY_TYPE_GROUP);
        map.put("buyWay", allPlace);
        commonSignUpdateAndInsert(map, 4);
        //时段
        allPlace.clear();
        allPlace.add(PlaceConstants.BUY_TYPE_TIME);
        map.put("buyWay", allPlace);
        map.put("finishDate","");//合同完成时间置空
        commonSignUpdateAndInsert(map, 5);
    }

    /**
     * 有效拜访和无效拜访统计
     * @param map
     * @param type
     */
    public void isVisitCommonUpdateAndInsert(Map<String, Object> map,Integer type){
        List<PlaceVisitStatisVo> effectVisitList = tbBizPlaceBusinessRewardRuleManagerMapper.selectIsEffectiveByCondition(map);
        try {
            for (PlaceVisitStatisVo visitStatisVo : effectVisitList) {
                Integer uid = visitStatisVo.getUid();
                visitStatisVo.setType(type);
                List<TbBizPlaceBusinessAgentStatistics> list = isNotExistAndExist(uid);
                //该条记录存在则更新，否则插入
                if (null != list && list.size() > 0) {
                    updateAgentStatis(visitStatisVo);
                } else {
                    insertAgentStatis(visitStatisVo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     *  签约场馆（整场，包片，时段）
     * @param map
     * @param type
     * @return
     */
    public void commonSignUpdateAndInsert(Map<String, Object> map,Integer type){
        List<PlaceVisitStatisVo> allPlaceList = tbBizPlaceBusinessRewardRuleManagerMapper.selectPlaceTypeByCondition(map);
        for (PlaceVisitStatisVo visitStatisVo : allPlaceList) {
            //根据场馆id确定用户uid
            Integer placeId = visitStatisVo.getPlaceId();
            TbBizPlaceRepresent tbBizPlaceRepresent = getRepresent(placeId);
            if (null != tbBizPlaceRepresent ){
                Integer uid = tbBizPlaceRepresent.getUid();
                visitStatisVo.setType(type);
                visitStatisVo.setUid(uid);
                List<TbBizPlaceBusinessAgentStatistics> list = isNotExistAndExist(uid);
                //该条记录存在则更新，否则插入
                if (null != list && list.size() > 0) {
                    updateAgentStatis(visitStatisVo);
                } else {
                    insertAgentStatis(visitStatisVo);
                }
            }
        }
    }

    /**
     * 根据type插入不同的指标值
     * @param visitStatisVo
     * @return
     */
    public Integer insertAgentStatis(PlaceVisitStatisVo visitStatisVo){
        Integer type = visitStatisVo.getType();
        TbBizPlaceBusinessAgentStatistics statistics = new TbBizPlaceBusinessAgentStatistics();
        if (type == 1){
            //有效访问
            statistics.setEffectiveVisitCount(visitStatisVo.getCount());
            statistics.setTargetCount(0);
            statistics.setCompleteCount(0);
            statistics.setNewEffectiveVisitCount(0);
            statistics.setPlaceBuyCount(0);
            statistics.setPacketBuyCount(0);
            statistics.setTimesBuyCount(new BigDecimal(0));
        }else if (type == 2){
            //新有效访问
            statistics.setNewEffectiveVisitCount(visitStatisVo.getCount());
            statistics.setTargetCount(0);
            statistics.setCompleteCount(0);
            statistics.setEffectiveVisitCount(0);
            statistics.setPlaceBuyCount(0);
            statistics.setPacketBuyCount(0);
            statistics.setTimesBuyCount(new BigDecimal(0));
        }else if (type == 3){
            //整场买入
            statistics.setPlaceBuyCount(visitStatisVo.getCount());
            statistics.setTargetCount(0);
            statistics.setCompleteCount(0);
            statistics.setPacketBuyCount(0);
            statistics.setEffectiveVisitCount(0);
            statistics.setNewEffectiveVisitCount(0);
            statistics.setTimesBuyCount(new BigDecimal(0));
        }else if (type == 4){
            //包片买入
            statistics.setPacketBuyCount(visitStatisVo.getCount());
            statistics.setTargetCount(0);
            statistics.setCompleteCount(0);
            statistics.setEffectiveVisitCount(0);
            statistics.setNewEffectiveVisitCount(0);
            statistics.setPlaceBuyCount(0);
            statistics.setTimesBuyCount(new BigDecimal(0));
        }else if (type == 5){
            //时段买入
            statistics.setTimesBuyCount(new BigDecimal(visitStatisVo.getCount()));
            statistics.setTargetCount(0);
            statistics.setCompleteCount(0);
            statistics.setEffectiveVisitCount(0);
            statistics.setNewEffectiveVisitCount(0);
            statistics.setPlaceBuyCount(0);
            statistics.setPacketBuyCount(0);
        }else if (type == 6){
            //城市经理目标数及完成目标数
            statistics.setTargetCount(visitStatisVo.getTargetCount());
            statistics.setCompleteCount(visitStatisVo.getCompleteCount());
            statistics.setEffectiveVisitCount(0);
            statistics.setNewEffectiveVisitCount(0);
            statistics.setPlaceBuyCount(0);
            statistics.setPacketBuyCount(0);
            statistics.setTimesBuyCount(new BigDecimal(0));
        }
        Integer uid = visitStatisVo.getUid();
        statistics.setUid(uid);
        statistics.setYear(String.valueOf(DateTimeUtils.getYear()));
        statistics.setMonth(String.valueOf(DateTimeUtils.getMonth()));
        //根据uid获取用户的role_type
        TbBizPlaceEmployee tbBizPlaceEmployee = getEmployeeByUid(uid);
        if (null != tbBizPlaceEmployee){
            statistics.setUserRoleType((byte)tbBizPlaceEmployee.getTitle().intValue());
        }
        statistics.setCreateTime(DateTimeUtils.getCurrentDate());
        return tbBizPlaceBusinessAgentStatisticsMapper.insert(statistics);
    }

    /**
     * 根据不同的参数类型更新统计指标
     * @param visitStatisVo
     * @return
     */
    public Integer updateAgentStatis(PlaceVisitStatisVo visitStatisVo){
        Integer type = visitStatisVo.getType();
        TbBizPlaceBusinessAgentStatistics statistics = new TbBizPlaceBusinessAgentStatistics();
        if (type == 1){
            //有效访问
            statistics.setEffectiveVisitCount(visitStatisVo.getCount());
        }else if (type == 2){
            //新有效访问
            statistics.setNewEffectiveVisitCount(visitStatisVo.getCount());
        }else if (type == 3){
            //整场买入
            statistics.setPlaceBuyCount(visitStatisVo.getCount());
        }else if (type == 4){
            //包片买入
            statistics.setPacketBuyCount(visitStatisVo.getCount());
        }else if (type == 5){
            //时段买入
            statistics.setTimesBuyCount(new BigDecimal(visitStatisVo.getCount()));
        }
        TbBizPlaceBusinessAgentStatisticsExample statisticsExample = new TbBizPlaceBusinessAgentStatisticsExample();
        TbBizPlaceBusinessAgentStatisticsExample.Criteria statisticsCriteria =statisticsExample.createCriteria();
        statisticsCriteria.andUidEqualTo(visitStatisVo.getUid());
        statisticsCriteria.andYearEqualTo(String.valueOf(DateTimeUtils.getYear()));
        statisticsCriteria.andMonthEqualTo(String.valueOf(DateTimeUtils.getMonth()));
        return tbBizPlaceBusinessAgentStatisticsMapper.updateByExampleSelective(statistics, statisticsExample);
    }

    /**
     * 商务代表奖金计算
     * 奖金 = （底薪+过程奖）*奖金系数+流水奖
     * 过程奖 = 拜访次数>=20
     *
     */
    @Override
    public void insertAgentAward() {
        //null表示用户uid为null，根据时间段只查询上月数据
        List<TbBizPlaceBusinessAgentStatistics>  agentStatistics = isNotExistAndExist(null);
        for (TbBizPlaceBusinessAgentStatistics tempAgentStatistics:agentStatistics){
            //用户uid
            Integer uid =  tempAgentStatistics.getUid();
            //月奖金
            BigDecimal monthAward = null;

            //过程奖 = 有效拜访奖 + 新有效拜访奖
            BigDecimal processAward = null;
            //流水奖
            BigDecimal waterAward = null;
            //有效拜访奖
            BigDecimal visitAward = null;
            //有效拜访次数
            Integer effectCount = tempAgentStatistics.getEffectiveVisitCount();
            if (null != effectCount){
                TbBizPlaceBusinessRewardRule rewardRule = getRewardRule((byte)PlaceConstants.TITLE_BUSSINESS_REPRESENT.intValue(), 3, 1);
                Integer paramMinValue = rewardRule.getParamMinValue().intValue();
                if (effectCount >= paramMinValue){
                    BigDecimal effectCoefficient = rewardRule.getCoefficientValue();
                    visitAward = effectCoefficient;
                }
            }

            //新有效拜访奖
            BigDecimal newVisitAward = null;
            //新有效拜访记录数
            Integer newEffectCount = tempAgentStatistics.getNewEffectiveVisitCount();
            if (null != newEffectCount){
                TbBizPlaceBusinessRewardRule rewardRule = getRewardRule((byte)PlaceConstants.TITLE_BUSSINESS_REPRESENT.intValue(), 3, 2);
                Integer paramMinValue = rewardRule.getParamMinValue().intValue();
                if (newEffectCount >= paramMinValue ){
                    BigDecimal effectCoefficient = rewardRule.getCoefficientValue();
                    newVisitAward = effectCoefficient;
                }
            }

            //获取用户底薪
            ReqBusinessAwardVo reqBusinessAwardVo = new ReqBusinessAwardVo();
            reqBusinessAwardVo.setUid(uid);
            TbBizPlaceEmployee employee = getEmployeeInfo(reqBusinessAwardVo).get(0);
            BigDecimal basicSalary = employee.getBasicSalary();

            if (null == processAward){
                processAward = new BigDecimal(0);
            }
            if (null != visitAward ){
                processAward = processAward.add(visitAward);
            }
            if (null != newVisitAward ){
                processAward = processAward.add(newVisitAward);
            }
            if (null != basicSalary ){
                processAward = processAward.add(basicSalary);
            }

            //获取上个月整场
            TbBizPlaceBusinessAgentStatistics agentStatistics1 = getLastMonthAgentStatis(uid,1);
            //整馆买入
            int placeCount = 0;
            if (null != agentStatistics1){
                placeCount = agentStatistics1.getPlaceBuyCount().intValue();
            }
            //获取奖金系数
            BigDecimal rewardEffective = null;
            //如果用户入职时间小于2个月，则系数按银牌算，则15%，否则按具体区间确定奖金系数
            Long entryTime = employee.getEntryTime().getTime();
            Long currentTime = System.currentTimeMillis();
            if (currentTime - entryTime < 5356800000L){
                //获取奖金系数-银牌值
                TbBizPlaceBusinessRewardRule rewardRule = getRewardRule((byte)PlaceConstants.TITLE_BUSSINESS_REPRESENT.intValue(),1,2);
                rewardEffective =  rewardRule.getCoefficientValue().divide(new BigDecimal(100));
            }else{
                //获取奖金系数所有区间参数值，然后根据用户的（场馆数）来确定用户等级（金，银，铜）
                ReqBusinessAwardVo reqBusinessAwardVo1 = new ReqBusinessAwardVo();
                reqBusinessAwardVo1.setTagGroup(1);
                reqBusinessAwardVo1.setUserRoleType((byte)PlaceConstants.TITLE_BUSSINESS_REPRESENT.intValue());
                List<TbBizPlaceBusinessRewardRule> buyTypeList = getRewardRuleByCondition(reqBusinessAwardVo1);
                Collections.reverse(buyTypeList);
                for (TbBizPlaceBusinessRewardRule rewardRule1 : buyTypeList){
                    if (null == rewardEffective){
                        int minValue = rewardRule1.getParamMinValue().intValue();
                        if (null != rewardRule1.getParamMaxValue()){
                            int maxValue = new BigDecimal(rewardRule1.getParamMaxValue()).intValue();
                            if (placeCount > minValue && placeCount <= maxValue){
                                rewardEffective = rewardRule1.getCoefficientValue().divide(new BigDecimal(100));
                            }
                        }else if (placeCount > minValue){
                            rewardEffective = rewardRule1.getCoefficientValue().divide(new BigDecimal(100));
                        }
                    }
                }
            }

            //流水奖 = 场馆的营业额*营业流水系数
            //获取上个月签订整馆的营业额
            BigDecimal revenues = getPlaceVisited(uid);
            //流水系数
            BigDecimal waterAwardParams = null;
            TbBizPlaceBusinessRewardRule waterAwardRule = getRewardRule((byte)PlaceConstants.TITLE_BUSSINESS_REPRESENT.intValue(),5,1);
            if (waterAwardRule.getValueType() == 4){
                waterAwardParams = waterAwardRule.getCoefficientValue().divide(new BigDecimal(100));
            }
            if (null == waterAward){
                waterAward = new BigDecimal(0);
            }
            //计算流水奖
            if (null != revenues){
                waterAward = revenues.multiply(waterAwardParams);
            }

            //计算月奖金总和
            if (null != waterAward){
                monthAward = (processAward.multiply(rewardEffective)).add(waterAward);
            }

            TbBizPlaceBusinessUserReward tbBizPlaceBusinessUser = new TbBizPlaceBusinessUserReward();
            tbBizPlaceBusinessUser.setUid(uid);
            //根据用户uid（主键）查询用户对象
            TbAdminUser tbAdminUser = getAdminUser(uid);
            if (null != tbAdminUser){
                tbBizPlaceBusinessUser.setUserName(tbAdminUser.getTrueName());
                tbBizPlaceBusinessUser.setCityId(tbAdminUser.getCityId());
            }
            tbBizPlaceBusinessUser.setUserRoleType((byte) PlaceConstants.TITLE_BUSSINESS_REPRESENT.intValue());//用户角色商务代表：5
            tbBizPlaceBusinessUser.setMonth(String.valueOf(DateTimeUtils.getMonth()));
            tbBizPlaceBusinessUser.setYear(String.valueOf(DateTimeUtils.getYear()));
            tbBizPlaceBusinessUser.setLowWage(basicSalary);//底薪
            tbBizPlaceBusinessUser.setMonthAward(monthAward);//月奖金
            tbBizPlaceBusinessUser.setPrizeOne(waterAward);//流水奖
            tbBizPlaceBusinessUser.setCreateTime(new Date());
            tbBizPlaceBusinessUserMapper.insert(tbBizPlaceBusinessUser);
        }
    }

    /**
     * 计算商务主管奖金 = 团队奖+破蛋奖+达标奖
     *
     */
    @Override
    public void insertBusinessManagerAward() {
        //1 获取所有的商务主管
        ReqBusinessAwardVo reqBusinessAwardVo = new ReqBusinessAwardVo();
        reqBusinessAwardVo.setUserRoleType((byte)PlaceConstants.TITLE_BUSSINESS_DIRECTOR.intValue());
        List<TbBizPlaceEmployee>  employeesList = getEmployeeInfo(reqBusinessAwardVo);
        for (TbBizPlaceEmployee employee:employeesList){
            Integer uid = employee.getUid();

            //获取商务主管是下级（商务代表）
            Integer employeeId = employee.getId();
            reqBusinessAwardVo.setUserRoleType((byte)PlaceConstants.TITLE_BUSSINESS_REPRESENT.intValue());
            reqBusinessAwardVo.setParentId(employeeId);
            List<TbBizPlaceEmployee>  employeesList1 = getEmployeeInfo(reqBusinessAwardVo);
            //团队奖
            BigDecimal groupReward = null;
            //达标奖
            BigDecimal targetReward = new BigDecimal(0);
            //破蛋奖
            Integer getEggReward = 0;
            //月奖金
            BigDecimal  monthAward = null;

            if (!employeesList1.isEmpty()){
                List<Integer> agentUidList = new ArrayList<>();
                for (TbBizPlaceEmployee employee1 : employeesList1){
                    agentUidList.add(employee1.getUid());
                }
                Map<String,Object> map = new HashMap<>();
                map.put("uid",agentUidList);
                map.put("year",DateTimeUtils.getYear());
                map.put("month",DateTimeUtils.getMonth());
                //获取上月商务代表的月奖金总和
                BigDecimal  agentMonthAward = tbBizPlaceBusinessRewardRuleManagerMapper.getAgentMonthAward(map);
                if (null != agentMonthAward){
                    //获取团队奖的系数
                    TbBizPlaceBusinessRewardRule waterAwardRule = getRewardRule((byte)PlaceConstants.TITLE_BUSSINESS_DIRECTOR.intValue(),7,1);
                    BigDecimal monthCoefficient = waterAwardRule.getCoefficientValue().divide(new BigDecimal(100));
                    //团队奖的总额百分比，为商务主管的奖金
                    groupReward = agentMonthAward.multiply(monthCoefficient);
                }

                //破蛋奖计算：整馆和时段 比如整馆2个，时段1个
                //个数计算规则：整馆个数*整馆个数定义+时段*时段个数定义 2*1+1*0.5=2.5，这里2.5取整为2，
                //破蛋奖计算规则：个数*破蛋系数 即：2*500 = 1000

                //破蛋个数
                Integer eggCount = 0;
                //场馆个数
                Integer placeCount = 0;
                //场馆计算值 = 场馆个数 * 整馆系数
                Integer placeValues = null;
                if(null != tbBizPlaceBusinessRewardRuleManagerMapper.getAgentBuyPlaceCount(map)){
                    placeCount = tbBizPlaceBusinessRewardRuleManagerMapper.getAgentBuyPlaceCount(map).intValue();
                    TbBizPlaceBusinessRewardRule waterAwardRule = getRewardRule((byte)PlaceConstants.TITLE_BUSSINESS_REPRESENT.intValue(),4,1);
                    BigDecimal placeCountCoefficient = waterAwardRule.getCoefficientValue();
                    placeValues = placeCountCoefficient.intValue() * placeCount;
                }
                //获取时段值 = 时段个数 * 时段系数 （时段个数取整）比如2.5 取2,2.8 也取2
                BigDecimal timesCounts = null;
                if(null != tbBizPlaceBusinessRewardRuleManagerMapper.getAgentBuyTimesCount(map)){
                    Integer timesCount = tbBizPlaceBusinessRewardRuleManagerMapper.getAgentBuyTimesCount(map).intValue();
                    TbBizPlaceBusinessRewardRule waterAwardRule = getRewardRule((byte)PlaceConstants.TITLE_BUSSINESS_REPRESENT.intValue(),4,2);
                    BigDecimal placeCountCoefficient = waterAwardRule.getCoefficientValue();
                    timesCounts = placeCountCoefficient.multiply(new BigDecimal(timesCount));
                }
                if (null != placeValues){
                    eggCount = placeValues;
                }
                if (null != timesCounts){
                    eggCount+=(int)Math.floor(timesCounts.doubleValue());
                }
                //获取破蛋奖的系数
                TbBizPlaceBusinessRewardRule waterAwardRule = getRewardRule((byte)PlaceConstants.TITLE_BUSSINESS_DIRECTOR.intValue(),8,2);//TODO
                Integer eggReward = waterAwardRule.getCoefficientValue().intValue();
                if (null != eggCount){
                    getEggReward = eggCount*eggReward;
                }

                //达标奖 1：整馆 2：时段
                Map<String,Object> mapContract = new HashMap<>();
                mapContract.put("uid",agentUidList);
                mapContract.put("beginTime",DateTimeUtils.getBeforeFirstMonthdate());
                mapContract.put("endTime",DateTimeUtils.getBeforeLastMonthdate());
                mapContract.put("finishDate",new Date());
                //1 整馆年限
                Integer placeExpires = tbBizPlaceBusinessRewardRuleManagerMapper.getPlaceBuyContract(mapContract);
                int placeHours = 0;
                if (null != placeExpires){
                    placeHours = placeExpires.intValue()*54*42;
                }
                //2 时段
                Integer primeHours = 0;
                //根据uid查询（buyWay为3）并且（上月签订）及（场馆可用）的场馆placeId
                map.put("uid",agentUidList);
                map.put("beginTime", DateTimeUtils.getBeforeFirstMonthdate());
                map.put("endTime", DateTimeUtils.getBeforeLastMonthdate());
                List<Integer> placeIdList = tbBizPlaceBusinessRewardRuleManagerMapper.getPlaceIdByUid(map);
                if (null != placeIdList && placeIdList.size()>0){
                    map.put("placeId",placeIdList);
                    //根据场馆id查询周一到周五黄金时段
                    Integer monToFriHours = tbBizPlaceBusinessRewardRuleManagerMapper.getMonToFriPrimeTimes(map);
                    if (null != monToFriHours){
                        primeHours += monToFriHours;
                    }
                    //根据场馆id查询周六到周天黄金时段
                    Integer satToSunHours = tbBizPlaceBusinessRewardRuleManagerMapper.getSatToSunPrimeTimes(map);
                    if (null != satToSunHours){
                        primeHours += satToSunHours;
                    }
                }
                if (null != primeHours){
                    placeHours += primeHours;
                }

                map.put("checkTime",DateTimeUtils.getBeforeDateYYMM());
                //获取商务代表目标数
                Integer agentTargetCount = tbBizPlaceBusinessRewardRuleManagerMapper.getAgentTarget(map);
                if (null != agentTargetCount){
                    if (placeHours > agentTargetCount){
                        //达标奖系数
                        TbBizPlaceBusinessRewardRule targetRewardCoefficient = getRewardRule((byte)PlaceConstants.TITLE_BUSSINESS_DIRECTOR.intValue(),9,3); //TODO
                        BigDecimal coefficientValue = targetRewardCoefficient.getCoefficientValue();
                        if (null != coefficientValue){
                            targetReward = targetReward.add(coefficientValue);
                        }
                    }
                }

                //月奖金
                if (null == monthAward){
                    monthAward = new BigDecimal(0);
                }
                if (null != groupReward ){
                    monthAward = monthAward.add(groupReward);
                }
                if (null != getEggReward ){
                    monthAward = monthAward.add(new BigDecimal(getEggReward));
                }
                if (null != targetReward ){
                    monthAward = monthAward.add(targetReward);
                }
            }else{
                //团队奖
                 groupReward = new BigDecimal(0);
                //达标奖
                 targetReward =  new BigDecimal(0);
                //破蛋奖
                 getEggReward =  0;
                //月奖金
                 monthAward =  new BigDecimal(0);
            }

            TbBizPlaceBusinessUserReward tbBizPlaceBusinessUser = new TbBizPlaceBusinessUserReward();
            tbBizPlaceBusinessUser.setUid(uid);
            TbAdminUser tbAdminUser = getAdminUser(employeeId);
            if (null != tbAdminUser){
                tbBizPlaceBusinessUser.setUserName(tbAdminUser.getTrueName());
                tbBizPlaceBusinessUser.setCityId(tbAdminUser.getCityId());
            }
            tbBizPlaceBusinessUser.setUserRoleType((byte)PlaceConstants.TITLE_BUSSINESS_DIRECTOR.intValue());
            tbBizPlaceBusinessUser.setMonth(String.valueOf(DateTimeUtils.getMonth()));
            tbBizPlaceBusinessUser.setYear(String.valueOf(DateTimeUtils.getYear()));
            tbBizPlaceBusinessUser.setCreateTime(new Date());
            //团队奖
            if (null != groupReward ){
                tbBizPlaceBusinessUser.setPrizeOne(groupReward);
            }else{
                tbBizPlaceBusinessUser.setPrizeOne(new BigDecimal(0));
            }
            //破蛋奖
            if (null != getEggReward ){
                tbBizPlaceBusinessUser.setPrizeTwo(new BigDecimal(getEggReward));
            }else{
                tbBizPlaceBusinessUser.setPrizeTwo(new BigDecimal(0));
            }
            //达标奖
            if (null != targetReward ){
                tbBizPlaceBusinessUser.setPrizeThree(targetReward);
            }else{
                tbBizPlaceBusinessUser.setPrizeThree(new BigDecimal(0));
            }
            //月奖金
            if (null != monthAward ){
                tbBizPlaceBusinessUser.setMonthAward(monthAward);
            }else{
                tbBizPlaceBusinessUser.setMonthAward(new BigDecimal(0));
            }
            tbBizPlaceBusinessUserMapper.insert(tbBizPlaceBusinessUser);
        }

    }

    /**
     * 计算城市经理奖金
     * 奖金 = 奖金基数 * 指标达成系数 + 管理奖
     */
    @Override
    public void insertCityManagerAward() {
        //获取城市经理
        ReqBusinessAwardVo reqBusinessAwardVo = new ReqBusinessAwardVo();
        reqBusinessAwardVo.setUserRoleType((byte)PlaceConstants.TITLE_BUSSINESS_CITY_MANAGER.intValue());
        List<TbBizPlaceEmployee>  employeesList = getEmployeeInfo(reqBusinessAwardVo);
        for (TbBizPlaceEmployee employee:employeesList){
            //获取城市经理底薪（奖金基数）
            BigDecimal citySalary = employee.getBasicSalary();
            Integer id = employee.getId();
            Integer uid = employee.getUid();
            reqBusinessAwardVo.setUserRoleType((byte)PlaceConstants.TITLE_BUSSINESS_DIRECTOR.intValue());
            reqBusinessAwardVo.setParentId(id);
            //城市经理管理的商务代表
            List<TbBizPlaceEmployee>  employeesList1 = getEmployeeInfo(reqBusinessAwardVo);
            if (null != employeesList1 && employeesList1.size()>0){
                List<Integer> uidList = new ArrayList<>();
                for (TbBizPlaceEmployee employee1:employeesList1){
                    uidList.add(employee1.getUid());
                }
                // 1：整馆
                Map<String,Object> mapContract = new HashMap<>();
                mapContract.put("uid",uidList);
                mapContract.put("beginTime",DateTimeUtils.getBeforeFirstMonthdate());
                mapContract.put("endTime",DateTimeUtils.getBeforeLastMonthdate());
                mapContract.put("finishDate",new Date());
                //获取商务代表签订 整馆年限
                Integer placeExpires = tbBizPlaceBusinessRewardRuleManagerMapper.getPlaceBuyContract(mapContract);
                int placeHours = 0;// TODO 完成的目标数
                if (null != placeExpires){
                    placeHours = placeExpires.intValue()*54*42;
                }

                //2 时段
                int primeHours = 0;
                //根据uid查询（buyWay为3）并且（上月签订）及（场馆可用）的场馆placeId
                List<Integer> placeIdList = tbBizPlaceBusinessRewardRuleManagerMapper.getPlaceIdByUid(mapContract);
                if (null != placeIdList && placeIdList.size()>0){
                    mapContract.put("placeId",placeIdList);
                    Integer monToFriHours = tbBizPlaceBusinessRewardRuleManagerMapper.getMonToFriPrimeTimes(mapContract);
                    if (null != monToFriHours){
                        primeHours += monToFriHours.intValue();
                    }
                    Integer satToSunHours = tbBizPlaceBusinessRewardRuleManagerMapper.getSatToSunPrimeTimes(mapContract);
                    if (null != satToSunHours){
                        primeHours += satToSunHours.intValue();
                    }
                }
                if (0 != primeHours){
                    placeHours += primeHours;
                }

                //获取商务代表目标黄金小时数
                Map<String,Object> map = new HashMap<>();
                map.put("uid",uidList);
                map.put("checkTime",DateTimeUtils.getBeforeDateYYMM());
                //获取商务代表指标
                Integer agentTargetCount = tbBizPlaceBusinessRewardRuleManagerMapper.getAgentTarget(map);//TODO 达成目标数

                //添加到统计表
                PlaceVisitStatisVo visitStatisVo = new PlaceVisitStatisVo();
                visitStatisVo.setType(6);
                visitStatisVo.setTargetCount(agentTargetCount == null ? Integer.valueOf(0) : agentTargetCount);
                visitStatisVo.setCompleteCount(placeHours);
                visitStatisVo.setUid(uid);
                insertAgentStatis(visitStatisVo);

                Integer percent = 0;
                if (null != agentTargetCount){
                    //计算用户达标率
                     percent = (placeHours/agentTargetCount)*100;
                }
                ReqBusinessAwardVo reqBusinessAwardVo1 = new ReqBusinessAwardVo();
                reqBusinessAwardVo1.setTagGroup(2);
                reqBusinessAwardVo1.setUserRoleType((byte)PlaceConstants.TITLE_BUSSINESS_CITY_MANAGER.intValue());
                List<TbBizPlaceBusinessRewardRule> buyTypeList = getRewardRuleByCondition(reqBusinessAwardVo1);
                //获取城市经理指标达成系数
                BigDecimal cityManagerCoefficientValue = null;
                for (TbBizPlaceBusinessRewardRule rewardRule1 : buyTypeList){
                    if (null == cityManagerCoefficientValue){
                        Integer minValue = rewardRule1.getParamMinValue().intValue();
                        if (null != rewardRule1.getParamMaxValue()){
                            Long maxValue = rewardRule1.getParamMaxValue();
                            if (minValue >= percent && percent < maxValue){
                                cityManagerCoefficientValue = rewardRule1.getCoefficientValue();
                            }
                        }else{
                            if (minValue > percent){
                                cityManagerCoefficientValue = rewardRule1.getCoefficientValue();
                            }
                        }
                    }
                }

                TbBizPlaceBusinessRewardRule cityManagerSalary = getRewardRule((byte)PlaceConstants.TITLE_BUSSINESS_CITY_MANAGER.intValue(),6,1); // TODO
                //管理奖
                BigDecimal cityManagerReward = cityManagerSalary.getCoefficientValue();
                if (null == cityManagerReward){
                    cityManagerReward = new BigDecimal(0);
                }
                BigDecimal monthAward = null;
                //本月奖金
                if (null != citySalary){
                    monthAward = citySalary.multiply(cityManagerCoefficientValue).add(cityManagerReward);
                }

                TbBizPlaceBusinessUserReward tbBizPlaceBusinessUser = new TbBizPlaceBusinessUserReward();
                tbBizPlaceBusinessUser.setUid(uid);
                TbAdminUser tbAdminUser = getAdminUser(uid);
                if (null != tbAdminUser){
                    tbBizPlaceBusinessUser.setUserName(tbAdminUser.getTrueName());
                    tbBizPlaceBusinessUser.setCityId(tbAdminUser.getCityId());
                }
                tbBizPlaceBusinessUser.setUserRoleType((byte)PlaceConstants.TITLE_BUSSINESS_CITY_MANAGER.intValue());//城市经理角色
                tbBizPlaceBusinessUser.setMonth(String.valueOf(DateTimeUtils.getMonth()));
                tbBizPlaceBusinessUser.setYear(String.valueOf(DateTimeUtils.getYear()));
                tbBizPlaceBusinessUser.setCreateTime(new Date());
                //奖金基数
                if(null != citySalary){
                    tbBizPlaceBusinessUser.setLowWage(citySalary);
                }else{
                    tbBizPlaceBusinessUser.setLowWage(new BigDecimal(0));
                }
                //管理奖
                tbBizPlaceBusinessUser.setPrizeOne(cityManagerReward);
                //月奖金
                if (null != monthAward ){
                    tbBizPlaceBusinessUser.setMonthAward(monthAward);
                }else{
                    tbBizPlaceBusinessUser.setMonthAward(new BigDecimal(0));
                }
                tbBizPlaceBusinessUserMapper.insert(tbBizPlaceBusinessUser);
            }
        }
    }


    /**
     * 获取用户的底薪及入职时间
     * @param reqBusinessAwardVo
     * @return
     */
    @Override
    public List<TbBizPlaceEmployee> getEmployeeInfo(ReqBusinessAwardVo reqBusinessAwardVo) {
        TbBizPlaceEmployeeExample employeeExample = new TbBizPlaceEmployeeExample();
        TbBizPlaceEmployeeExample.Criteria employeeExampleCriteria  = employeeExample.createCriteria();
        if (null != reqBusinessAwardVo.getUid() ){
            employeeExampleCriteria.andUidEqualTo(reqBusinessAwardVo.getUid());
        }
        if (null != reqBusinessAwardVo.getUserRoleType()){
            employeeExampleCriteria.andTitleEqualTo(Integer.valueOf(reqBusinessAwardVo.getUserRoleType()));
        }
        if (null != reqBusinessAwardVo.getEntryTime()){
            employeeExampleCriteria.andEntryTimeEqualTo(reqBusinessAwardVo.getEntryTime());
        }
        if (null != reqBusinessAwardVo.getParentId()){
            employeeExampleCriteria.andParentIdEqualTo(reqBusinessAwardVo.getParentId());
        }
        if (null != reqBusinessAwardVo.getCityId()){
            employeeExampleCriteria.andCityIdEqualTo(reqBusinessAwardVo.getCityId());
        }
        List<TbBizPlaceEmployee> employeesList = tbBizPlaceEmployeeMapper.selectByExample(employeeExample);
        if (null != employeesList && employeesList.size() >0){
            return employeesList;
        }
        return null;
    }


    /**
     * 根据id查询用户
     * @param uid
     * @return
     */
    public TbBizPlaceEmployee getEmployeeByUid(Integer uid){
        TbBizPlaceEmployeeExample tbBizPlaceEmployeeExample = new TbBizPlaceEmployeeExample();
        TbBizPlaceEmployeeExample.Criteria criteria = tbBizPlaceEmployeeExample.createCriteria();
        criteria.andUidEqualTo(uid);
        List<TbBizPlaceEmployee> tbBizPlaceEmployees = tbBizPlaceEmployeeMapper.selectByExample(tbBizPlaceEmployeeExample);
        if (null != tbBizPlaceEmployees && tbBizPlaceEmployees.size()>0){
           return tbBizPlaceEmployees.get(0);
        }
        return null;
    }


    /**
     * 获取奖金规则参数
     * @param userRoleType
     * @param tagGroup
     * @param paramKey
     * @return
     */
    public TbBizPlaceBusinessRewardRule getRewardRule(Byte userRoleType,Integer tagGroup,Integer paramKey){
        ReqBusinessAwardVo reqBusinessAwardVo = new ReqBusinessAwardVo();
        reqBusinessAwardVo.setUserRoleType(userRoleType);
        reqBusinessAwardVo.setTagGroup(tagGroup);
        reqBusinessAwardVo.setParamKey(paramKey);
        reqBusinessAwardVo.setIsEnabled(PlaceConstants.IS_EFFECTIVE_YES);
        TbBizPlaceBusinessRewardRule rewardRule = getRewardRuleByCondition(reqBusinessAwardVo).get(0);
        return rewardRule;
    }


    /**
     * 根据uid,年，月确定该用户是否有唯一记录
     * @param uid
     * @return
     */
    public List<TbBizPlaceBusinessAgentStatistics> isNotExistAndExist(Integer uid){
        TbBizPlaceBusinessAgentStatisticsExample statisticsExample = new TbBizPlaceBusinessAgentStatisticsExample();
        TbBizPlaceBusinessAgentStatisticsExample.Criteria statisticsCriteria =statisticsExample.createCriteria();
        if (null != uid ){
            statisticsCriteria.andUidEqualTo(uid);
            TbBizPlaceEmployee tbBizPlaceEmployee = getEmployeeByUid(uid);
            if (null != tbBizPlaceEmployee){
                statisticsCriteria.andUserRoleTypeEqualTo((byte)tbBizPlaceEmployee.getTitle().intValue());
            }
        }
        statisticsCriteria.andYearEqualTo(String.valueOf(DateTimeUtils.getYear()));
        statisticsCriteria.andMonthEqualTo(String.valueOf(DateTimeUtils.getMonth()));
        return tbBizPlaceBusinessAgentStatisticsMapper.selectByExample(statisticsExample);
    }

    /**
     * 根据场馆id确定商务代表uid
     * @param placeId
     * @return
     */
    public TbBizPlaceRepresent getRepresent(Integer placeId){
        TbBizPlaceRepresentExample tbBizPlaceRepresentExample = new TbBizPlaceRepresentExample();
        TbBizPlaceRepresentExample.Criteria criteria = tbBizPlaceRepresentExample.createCriteria();
        criteria.andPlaceIdEqualTo(placeId);
        List<TbBizPlaceRepresent> representsList = tbBizPlaceRepresentMapper.selectByExample(tbBizPlaceRepresentExample);
        if (null != representsList && representsList.size()>0){
            return representsList.get(0);
        }
        return null;
    }
    /**
     * 根据uid及年和月获取用户签订上月整场数
     * 比如 7月1号统计任务是6月份的数据，但整馆，时段获取5月份的数值
     * @param uid
     * @param type:0：本月数据，1：上月数据 因为计算整馆签订个数是获取上月个数，时段获取本月数据
     * @return
     */
    public TbBizPlaceBusinessAgentStatistics getLastMonthAgentStatis(Integer uid,Integer type){
        TbBizPlaceBusinessAgentStatisticsExample statisticsExample = new TbBizPlaceBusinessAgentStatisticsExample();
        TbBizPlaceBusinessAgentStatisticsExample.Criteria statisticsCriteria =statisticsExample.createCriteria();
        if (null != uid ){
            statisticsCriteria.andUidEqualTo(uid);
        }
        if (type == 0){
            statisticsCriteria.andMonthEqualTo(String.valueOf(DateTimeUtils.getMonth()));
        }else if (type == 1){
            statisticsCriteria.andMonthEqualTo(String.valueOf(DateTimeUtils.getMonth()-1));
        }
        statisticsCriteria.andYearEqualTo(String.valueOf(DateTimeUtils.getYear()));
        List<TbBizPlaceBusinessAgentStatistics> list = tbBizPlaceBusinessAgentStatisticsMapper.selectByExample(statisticsExample);
        if (!list.isEmpty()){
            return list.get(0);
        }
        return null;

    }

    /**
     * 获取场馆上月的营业流水收入
     * 1、根据uid查找用户所签订的场馆（placeID）
     * 2、根据场馆(placeID)在订单表中统计上月所得营业额
     * @param uid
     * @return
     */
    public BigDecimal getPlaceVisited(Integer uid){
        TbBizPlaceBuyContractDetailExample placeBuyContractDetailExample = new TbBizPlaceBuyContractDetailExample();
        TbBizPlaceBuyContractDetailExample.Criteria contractDetail = placeBuyContractDetailExample.createCriteria();
        List<Integer> buyWay = new ArrayList<>();
        buyWay.add(PlaceConstants.BUY_TYPE_WHOLE);// 1:整馆买入，2：包片买入，3：时段买入
        contractDetail.andUidEqualTo(uid);
        contractDetail.andBuyTypeIn(buyWay);
        contractDetail.andIsDeleteEqualTo((byte)0);
        contractDetail.andBuyDateGreaterThanOrEqualTo(DateTimeUtils.strToDateYYYYMMDDHHMMSS(DateTimeUtils.getBeforeFirstMonthdate()));
        contractDetail.andBuyDateLessThanOrEqualTo(DateTimeUtils.strToDateYYYYMMDDHHMMSS(DateTimeUtils.getBeforeLastMonthdate()));
        contractDetail.andFinishDateLessThanOrEqualTo(new Date());//合同是否到期
        //获取上月签订场馆（placeID）
        List<TbBizPlaceBuyContractDetail> placeBuyContractDetails = tbBizPlaceBuyContractDetailMapper.selectByExample(placeBuyContractDetailExample);
        List<Integer> placeIdList = new ArrayList<>();
        if (!placeBuyContractDetails.isEmpty()){
            for (TbBizPlaceBuyContractDetail detail:placeBuyContractDetails){
                    placeIdList.add(detail.getPlaceId());
            }
        }
        return getPlaceOrderDebit(placeIdList);
    }


    /**
     * 计算上月签订场馆营业额
     * @param placeId
     * @return
     */
    public BigDecimal getPlaceOrderDebit(List<Integer> placeId){
        Map<String,Object> map = new HashMap();
        if(null != placeId && placeId.size()>0){
            map.put("placeId",placeId);
            map.put("beginTime",DateTimeUtils.strToDateYYYYMMDDHHMMSS(DateTimeUtils.getBeforeFirstMonthdate()));
            map.put("endTime",DateTimeUtils.strToDateYYYYMMDDHHMMSS(DateTimeUtils.getBeforeLastMonthdate()));
            return tbBizPlaceBusinessRewardRuleManagerMapper.getPlaceOrderDebit(map);
        }
     return null;
    }


    /**
     * 获取商务代表列表
     * @param reqBusinessAwardVo
     * @return
     */
    @Override
    public PageObj<List<BusinessAwardUserVo>> getBusinessAgentAward(ReqBusinessAwardVo reqBusinessAwardVo) {
        Integer pageNum = 0;
        Integer pageSize = Constants.DEFAULT_PAGE_SIZE;
        Integer uid = null;
        if (reqBusinessAwardVo != null){
            pageNum = reqBusinessAwardVo.getPageNum();
            pageSize = reqBusinessAwardVo.getPageSize();
            uid = reqBusinessAwardVo.getUid();
        }
        if (null != uid ){
            TbBizPlaceEmployee tbBizPlaceEmployee = getEmployeeByUid(uid);
            if (null != tbBizPlaceEmployee) {
                Integer userType = tbBizPlaceEmployee.getTitle();
                reqBusinessAwardVo.setUserRoleType((byte) userType.intValue());
                if (userType.equals(PlaceConstants.TITLE_BUSSINESS_REPRESENT)) {
                    List<Integer> uids = new ArrayList<>();
                    uids.add(reqBusinessAwardVo.getUid());
                    reqBusinessAwardVo.setUids(uids);
                    //商务代表
                    Integer total = tbBizPlaceBusinessRewardRuleManagerMapper.countByCondition(reqBusinessAwardVo);
                    reqBusinessAwardVo.setPage(new Page(pageNum * pageSize, pageSize, total));
                    List<BusinessAwardUserVo> records = tbBizPlaceBusinessRewardRuleManagerMapper.getBusinessAgent(reqBusinessAwardVo);
                    PageObj<List<BusinessAwardUserVo>> result = PageObj.create(total, pageNum, pageSize, records);
                    return result;
                } else if (userType.equals(PlaceConstants.TITLE_BUSSINESS_DIRECTOR)) {
                    //商务主管：商务代表数据
                    ReqBusinessAwardVo reqBusinessAwardVo1 = new ReqBusinessAwardVo();
                    reqBusinessAwardVo1.setParentId(tbBizPlaceEmployee.getId());
                    //找到商务代表id
                    List<TbBizPlaceEmployee> agentEmployee = getEmployeeInfo(reqBusinessAwardVo1);
                    List<Integer> uids = new ArrayList<>();
                    for (TbBizPlaceEmployee getEmployee : agentEmployee) {
                        uids.add(getEmployee.getUid());
                    }
                    reqBusinessAwardVo.setUids(uids);
                    //商务代表
                    Integer total = tbBizPlaceBusinessRewardRuleManagerMapper.countByCondition(reqBusinessAwardVo);
                    reqBusinessAwardVo.setPage(new Page(pageNum * pageSize, pageSize, total));
                    List<BusinessAwardUserVo> records = tbBizPlaceBusinessRewardRuleManagerMapper.getBusinessAgent(reqBusinessAwardVo);
                    PageObj<List<BusinessAwardUserVo>> result = PageObj.create(total, pageNum, pageSize, records);
                    return result;
                }
            }
        }

        return null;
    }

    /**
     * 商务主管
     * @param reqBusinessAwardVo
     * @return
     */
    @Override
    public PageObj<List<BusinessAwardUserVo>> getBusinessManagerAward(ReqBusinessAwardVo reqBusinessAwardVo) {
        Integer pageNum = 0;
        Integer pageSize = Constants.DEFAULT_PAGE_SIZE;
        Integer uid = null;
        if (reqBusinessAwardVo != null){
            pageNum = reqBusinessAwardVo.getPageNum();
            pageSize = reqBusinessAwardVo.getPageSize();
            uid = reqBusinessAwardVo.getUid();
        }
        if (null != uid){
            TbBizPlaceEmployee tbBizPlaceEmployee = getEmployeeByUid(uid);
            if (null != tbBizPlaceEmployee){
                Integer userType = tbBizPlaceEmployee.getTitle();
                // reqBusinessAwardVo.setUserRoleType((byte)userType.intValue());
                if (userType.equals(PlaceConstants.TITLE_BUSSINESS_DIRECTOR)){
                    List<Integer> uids = new ArrayList<>();
                    uids.add(reqBusinessAwardVo.getUid());
                    reqBusinessAwardVo.setUids(uids);
                    //商务主管
                    Integer total = tbBizPlaceBusinessRewardRuleManagerMapper.getBusinessManagerCount(reqBusinessAwardVo);
                    reqBusinessAwardVo.setPage(new Page(pageNum * pageSize, pageSize, total));
                    List<BusinessAwardUserVo> records = tbBizPlaceBusinessRewardRuleManagerMapper.getBusinessManager(reqBusinessAwardVo);
                    PageObj<List<BusinessAwardUserVo>> result = PageObj.create(total, pageNum, pageSize, records);
                    return result;
                }else if (userType.equals(PlaceConstants.TITLE_BUSSINESS_CITY_MANAGER)){
                    //城市经理：商务主管数据
                    ReqBusinessAwardVo reqBusinessAwardVo1 = new ReqBusinessAwardVo();
                    reqBusinessAwardVo1.setParentId(tbBizPlaceEmployee.getId());
                    //找到商务主管id
                    List<TbBizPlaceEmployee> agentEmployee = getEmployeeInfo(reqBusinessAwardVo1);
                    List<Integer> uids = new ArrayList<>();
                    for (TbBizPlaceEmployee getEmployee:agentEmployee){
                        uids.add(getEmployee.getUid());
                    }
                    reqBusinessAwardVo.setUids(uids);
                    //商务主管数据
                    Integer total = tbBizPlaceBusinessRewardRuleManagerMapper.getBusinessManagerCount(reqBusinessAwardVo);
                    reqBusinessAwardVo.setPage(new Page(pageNum * pageSize, pageSize, total));
                    List<BusinessAwardUserVo> records = tbBizPlaceBusinessRewardRuleManagerMapper.getBusinessManager(reqBusinessAwardVo);
                    PageObj<List<BusinessAwardUserVo>> result = PageObj.create(total, pageNum, pageSize, records);
                    return result;
                }
            }
        }


        return null;
    }

    /**
     * 城市经理
     * @param reqBusinessAwardVo
     * @return
     */
    @Override
    public PageObj<List<BusinessAwardUserVo>> getBusinessCityManagerAward(ReqBusinessAwardVo reqBusinessAwardVo) {
        Integer pageNum = 0;
        Integer pageSize = Constants.DEFAULT_PAGE_SIZE;
        Integer uid = null;
        if (reqBusinessAwardVo != null){
            pageNum = reqBusinessAwardVo.getPageNum();
            pageSize = reqBusinessAwardVo.getPageSize();
            uid = reqBusinessAwardVo.getUid();
        }
        if (null != uid){
            TbBizPlaceEmployee tbBizPlaceEmployee = getEmployeeByUid(uid);
            if (null != tbBizPlaceEmployee) {
                Integer userType = tbBizPlaceEmployee.getTitle();
                reqBusinessAwardVo.setUserRoleType((byte) userType.intValue());

                if (userType.equals(PlaceConstants.TITLE_BUSSINESS_CITY_MANAGER)) {
                    //城市经理
                    Integer total = tbBizPlaceBusinessRewardRuleManagerMapper.getCityManagerCount(reqBusinessAwardVo);
                    reqBusinessAwardVo.setPage(new Page(pageNum * pageSize, pageSize, total));
                    List<BusinessAwardUserVo> records = tbBizPlaceBusinessRewardRuleManagerMapper.getCityManager(reqBusinessAwardVo);
                    PageObj<List<BusinessAwardUserVo>> result = PageObj.create(total, pageNum, pageSize, records);
                    return result;
                }
            }
        }
        return null;
    }

    @Override
    public List<TbBizPlaceEmployee> getTbBizPlaceEmployee(ReqBusinessAwardVo reqBusinessAwardVo) {
       /* Integer pageNum = 0;
        Integer pageSize = Constants.DEFAULT_PAGE_SIZE;
        if (reqBusinessAwardVo != null){
            pageNum = reqBusinessAwardVo.getPageNum();
            pageSize = reqBusinessAwardVo.getPageSize();
        }*/
        TbBizPlaceEmployeeExample employeeExample = new TbBizPlaceEmployeeExample();
        TbBizPlaceEmployeeExample.Criteria employeeExampleCriteria  = employeeExample.createCriteria();
        if (null != reqBusinessAwardVo.getCityId()){
            employeeExampleCriteria.andCityIdEqualTo(reqBusinessAwardVo.getCityId());
        }
        if (null != reqBusinessAwardVo.getUserRoleType()){
            Integer userType = reqBusinessAwardVo.getUserRoleType().intValue();
            employeeExampleCriteria.andTitleEqualTo(userType);
        }
      //  Integer total = tbBizPlaceEmployeeMapper.countByExample(employeeExample);
        //employeeExample.setPage(new Page(pageNum * pageSize, pageSize, total));
        List<TbBizPlaceEmployee> records = tbBizPlaceEmployeeMapper.selectByExample(employeeExample);
       // PageObj<List<TbBizPlaceEmployee>> result = PageObj.create(total, pageNum, pageSize, records);
        return records;
    }

    @Override
    public Integer updateBatchUserSalary(ReqBusinessAwardVo reqBusinessAwardVo) {
        return tbBizPlaceBusinessRewardRuleManagerMapper.updateBatchUserSalary(reqBusinessAwardVo);
    }


    public TbAdminUser getAdminUser(Integer uid){
        TbAdminUser tbAdminUser = tbAdminUserMapper.selectByPrimaryKey(uid);
        return tbAdminUser;
    }



}
